<template>
  <div class="page-container" v-loading="loading">
    <div class="add-wrap">
      <!-- <div class="header-section">
        <Breadcrumb :titles="titles"></Breadcrumb>
        <div class="title">
          数据月份：
          <el-date-picker
            v-model="select"
            type="month"
            @change="changeMonth"
            :clearable="false"
            placeholder="选择月"
          >
          </el-date-picker>
        </div>
      </div> -->

      <div class="search_header">
        <div class="search_header_left">
          <el-button
            icon="el-icon-download"
            @click="downloadFile"
            v-has="'fixedTargetMap:export'"
            >下载数据</el-button
          >

          <span class="tips">
            请于本月8日24点之前完成1-{{
              (select || '').split('-').at(1) || ''
            }}月的本年度累计完成固投
          </span>
        </div>

        <div class="search_header_right">
          <el-input
            placeholder="请输入项目名称、业主"
            v-model="parameter.keywords"
            @keydown.enter.native="search"
            @clear="search"
            clearable
          >
            <span
              @click="search"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
          <el-date-picker
            @change="changeMonth"
            v-model="select"
            type="month"
            placeholder="月份"
            value-format="yyyy-M"
            :clearable="false"
            @clear="search"
            :picker-options="pickerOptions"
          />
          <!-- <el-select
            placeholder="批次"
            v-model="parameter.batchNo"
            clearable
            @change="search"
          >
            <el-option
              v-for="item in batchSelectionOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <el-select
            placeholder="状态"
            v-model="parameter.projectStatus"
            clearable
            @change="search"
            @clear="search"
          >
            <el-option
              v-for="item in projectStatusOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select> -->
          <el-select
            placeholder="项目类型"
            v-model="parameter.projectType"
            clearable
            @change="search"
            @clear="search"
          >
            <el-option
              v-for="item in projectTypeListOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </div>
      </div>

      <div class="table-section">
        <el-table
          :data="tableData"
          :header-cell-style="{
            background: '#F2F6FB',
            color: ' #6B767D'
          }"
          height="100%"
        >
          <el-table-column
            label="项目名称"
            prop="projectName"
            width="400"
            show-overflow-tooltip
          />
          <el-table-column
            label="本年度计划完成固投(万元)"
            prop="fixedTotal"
            show-overflow-tooltip
          />
          <el-table-column
            label="一季度计划固投(万元)"
            prop="fixedOne"
            show-overflow-tooltip
          />
          <el-table-column
            label="二季度计划固投(万元)"
            prop="fixedTwo"
            show-overflow-tooltip
          />
          <el-table-column
            label="三季度计划固投(万元)"
            prop="fixedThree"
            show-overflow-tooltip
          />
          <el-table-column
            label="四季度计划固投(万元)"
            prop="fixedFour"
            show-overflow-tooltip
          />
          <el-table-column
            label="上月累计完成固投(万元)"
            prop="lastMonthFixedTotalInvestment"
            show-overflow-tooltip
          />
          <el-table-column label="本年度累计完成固投(万元)">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.fixedTotalInvestment"
                type="number"
                :disabled="
                  !editable && !scope.row.isEditing
                "
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="凭证(pdf、png、jpg格式)">
            <template slot-scope="scope">
              <div class="upload-container">
                <el-upload
                  action=""
                  :auto-upload="false"
                  :show-file-list="false"
                  :before-upload="
                    (file) => beforeUpload(file)
                  "
                  :on-change="
                    (file) =>
                      handleUpload(
                        file,
                        scope.row,
                        scope.$index
                      )
                  "
                  multiple
                >
                  <template
                    v-if="
                      scope.row.fileType === 'image/png' ||
                      scope.row.fileType === 'image/jpeg'
                    "
                  >
                    <div class="image-preview" @click.stop>
                      <el-image
                        :src="scope.row.imagePreview"
                        style="width: 100px; height: 100px"
                        :preview-src-list="[
                          scope.row.imagePreview
                        ]"
                        fit="cover"
                      >
                        <template #error>
                          <div class="image-slot">
                            加载失败
                          </div>
                        </template>
                      </el-image>
                      <div
                        class="delete-circle"
                        @click.stop.prevent="
                          handleRemove(scope.row)
                        "
                      >
                        <i class="el-icon-close"></i>
                      </div>
                    </div>
                  </template>

                  <template
                    v-else-if="
                      scope.row.filePath &&
                      (getExt(scope.row.filePath) ===
                        'png' ||
                        getExt(scope.row.filePath) ===
                          'jpg' ||
                        getExt(scope.row.filePath) ===
                          'jpeg')
                    "
                  >
                    <div class="image-preview" @click.stop>
                      <el-image
                        :src="`${STATIC_FILE_URL}${scope.row.filePath}`"
                        style="width: 100px; height: 100px"
                        :preview-src-list="[
                          `${STATIC_FILE_URL}${scope.row.filePath}`
                        ]"
                        fit="cover"
                      >
                        <template #error>
                          <div class="image-slot">
                            加载失败
                          </div>
                        </template>
                      </el-image>
                      <div
                        class="delete-circle"
                        @click.stop.prevent="
                          handleRemove(scope.row)
                        "
                      >
                        <i class="el-icon-close"></i>
                      </div>
                    </div>
                  </template>

                  <template
                    v-else-if="
                      scope.row.fileType ===
                        'application/pdf' ||
                      getExt(scope.row.filePath) === 'pdf'
                    "
                  >
                    <div class="file-preview" @click.stop>
                      <span
                        class="file-name"
                        v-if="scope.row.fileName"
                        @click="
                          handleDownloadPdf(scope.row)
                        "
                        style="cursor: pointer"
                        >{{ scope.row.fileName }}</span
                      >
                      <span
                        class="file-name"
                        v-if="scope.row?.filePath"
                        @click="
                          handleDownloadPdf(scope.row)
                        "
                        style="cursor: pointer"
                        >{{
                          scope.row?.filePath
                            ?.split('/')
                            .pop()
                        }}</span
                      >
                      <div
                        class="delete-circle"
                        @click.stop.prevent="
                          handleRemove(scope.row)
                        "
                      >
                        <i class="el-icon-close"></i>
                      </div>
                    </div>
                  </template>

                  <div v-else>
                    <el-button
                      type="text"
                      :disabled="
                        !editable && !scope.row.isEditing
                      "
                      >上传</el-button
                    >
                  </div>
                </el-upload>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button
                v-has="'fixedTargetMap:track'"
                @click="handleReturn(scope.row)"
                type="text"
                style="color: #ff5b5b; font-weight: 400"
                v-if="!editable"
                >退回
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="line">
      <el-button
        v-if="
          editable ||
          tableData.some((item) => item.isEditing)
        "
        @click="saveInfo"
        class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import dayjs from 'dayjs'
import {
  queryFixedInfoByMonth,
  addFixedInfo,
  downloadFixedInfo,
  uploadFileById
} from '@/api/dataManagement'
import {
  batchSelectionOptions,
  projectTypeListOptions,
  projectStatusOptions
} from '@/utils/project/data'
import Icon from '@/components/icon'
import { downloadBlobFile } from '@/utils/download'
import { STATIC_FILE_URL } from '@/api/config'
import { isAfterMonth } from '@/utils/datetime'

export default {
  props: {
    title: String,
    projectId: String
  },
  components: {
    Breadcrumb,
    Icon
  },
  data() {
    return {
      tableData: [],
      select: '',
      parameter: {
        // pageIndex: 1,
        // pageSize: 999,
        keywords: '',
        year: '',
        projectType: '',
        month: ''
      },
      loading: false,
      pickerOptions: {
        disabledDate: (date) => {
          return isAfterMonth(date, new Date())
        }
      }
    }
  },
  computed: {
    /**
     * 是否可填写
     *
     * @description 所选日期为当前日期的上一个月，并且当前日期为9号之前
     */
    editable() {
      if (!this.select) {
        return false
      }
      const currentDate = dayjs().date()
      const isPreviousMonthSelected =
        dayjs().month() - dayjs(this.select).month() === 1
      return isPreviousMonthSelected && currentDate < 9
    },
    titles() {
      return [this.title]
    },
    batchSelectionOptions() {
      return batchSelectionOptions
    },
    projectTypeListOptions() {
      return projectTypeListOptions
    },
    projectStatusOptions() {
      return projectStatusOptions
    },
    STATIC_FILE_URL() {
      return STATIC_FILE_URL
    }
  },
  mounted() {
    const date = new Date()
    this.select = dayjs(date)
      .subtract(1, 'month')
      .format('YYYY-M')
    this.searchInfo()
  },
  methods: {
    changeMonth(val) {
      this.searchInfo()
    },
    search() {
      this.parameter.keywords =
        this.parameter.keywords?.trim?.() || ''
      // this.parameter.pageIndex = 1
      this.searchInfo()
    },
    searchInfo() {
      if (!this.select) {
        this.$message.error('请选择月份')
        return
      }
      const year = this.select.split('-')[0]
      const month = this.select.split('-')[1]
      this.parameter.month = month
      this.parameter.year = year
      queryFixedInfoByMonth(this.parameter)
        .then((res) => {
          if (res.success) {
            this.tableData = res.data.map((item) => {
              return {
                ...item,
                fileType: '',
                fileName: '',
                imagePicture: ''
                // evidencePicture: item.evidencePicture? item.evidencePicture : ''
              }
            })
          } else {
            this.$message.error(res.message || '查询失败')
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    getExt(path) {
      if (!path) return ''
      return path.split('/').pop().split('.').pop()
    },
    saveInfo() {
      if (!this.select) {
        this.$message.error('请选择月份')
        return
      }
      const year = this.select.split('-')[0]
      const month = this.select.split('-')[1]
      const params = this.tableData.map((item) => {
        return {
          projectId: item.projectId,
          year: year,
          month: month,
          fixedTotalInvestment: item.fixedTotalInvestment,
          evidencePicture: item.evidencePicture
        }
      })
      console.log('params', params)
      addFixedInfo(params)
        .then((res) => {
          if (res.success) {
            this.$message.success('保存成功')
            this.searchInfo()
            // this.$router.push({
            //   path: '/dataManagement/projectManagement/fixedTargetMap/list'
            // })
          } else {
            this.$message.error(res.message || '保存失败')
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // changeMonth(val) {
    //   this.select = dayjs(val).format('YYYY-M')
    //   this.searchInfo()
    // },
    downloadFile() {
      this.btnLoading = true
      downloadFixedInfo(this.parameter)
        .then((res) => {
          downloadBlobFile(res, '固投信息表.xlsx')
        })
        .catch((err) => {
          this.$message.error('下载失败')
        })
        .finally(() => {
          this.btnLoading = false
        })
    },
    handleDownloadPdf(row) {
      if (row.filePath) {
        const url = `${STATIC_FILE_URL}${row.filePath}`
        window.open(url, '_blank')
      } else {
        this.$message.warning('文件路径不存在')
      }
    },
    handleReturn(row) {
      // this.$confirm('确定要退回该条数据吗?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {

      //   this.$message({
      //     type: 'success',
      //     message: '已允许编辑该条数据'
      //   });
      // }).catch(() => {});
      this.$set(row, 'isEditing', true)
    },
    isImage(file, index) {
      if (!file) return false
      if (file && file.raw) {
        const fileType = file.raw.type
        this.$set(
          this.tableData[index],
          'fileType',
          fileType
        )
        return [
          'image/png',
          'image/jpeg',
          'application/pdf'
        ].includes(fileType)
      }
    },
    beforeUpload(file) {
      const isAcceptable = [
        'application/pdf',
        'image/png',
        'image/jpeg'
      ].includes(file.type)
      if (!isAcceptable) {
        this.$message.error('只能上传 pdf、jpg 或 png 文件')
        return false
      }
      return true
    },
    handleUpload(file, row, index) {
      if (!file) return

      const fileType = file.raw.type
      this.$set(this.tableData[index], 'fileType', fileType)
      this.$set(
        this.tableData[index],
        'fileName',
        file.raw.name
      )

      if (
        fileType === 'image/png' ||
        fileType === 'image/jpeg'
      ) {
        const objectUrl = URL.createObjectURL(file.raw)
        this.$set(
          this.tableData[index],
          'imagePreview',
          objectUrl
        )
      }

      const formData = new FormData()
      formData.append('file', file.raw)
      this.loading = true

      uploadFileById(formData)
        .then((res) => {
          if (res.success) {
            this.$set(
              this.tableData[index],
              'evidencePicture',
              res.data
            )
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleRemove(row) {
      if (
        row.imagePreview &&
        row.imagePreview.startsWith('blob:')
      ) {
        URL.revokeObjectURL(row.imagePreview)
      }

      row.filePath = ''
      row.fileType = ''
      row.fileName = ''
      row.imagePreview = null
      row.evidencePicture = ''
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/table.scss';
// @import '~@/assets/css/form.scss';

.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px 10px;
}

.add-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;

  // .body {
  //   width: 100%;
  //   display: flex;
  //   flex: 1;
  //   overflow: hidden;
  //   box-sizing: border-box;
  //   padding: 20px 10px;
  // }

  .title {
    margin: 15px 0;
  }

  .search_header_left {
    align-items: center;
    column-gap: 16px;

    .tips {
      font-size: 14px;
      color: #c93f3f;
    }
  }
}

.line {
  position: sticky;
  bottom: 0;
  width: calc(100% - 40px);
  padding-left: 30%;
  margin: 0 auto;
  right: 15px;
  background: #fff;
  border-top: 1px solid #eee;
  padding: 10px 0;
  display: flex;
  justify-content: center;
  z-index: 10;
}

.save-btn {
  background: #497fa3;
  border: 1px solid #497fa3;
  width: 104px;
  color: white;
  font-size: 14px;
  width: 104px;
  height: 34px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
}

.table-section {
  flex: 1;
  overflow: hidden;
}

.table-section ::v-deep .el-table__body-wrapper {
  overflow-y: auto !important;
}

// ::v-deep .el-input__inner {
//   max-width: 150px;
// }

.upload-container {
  position: relative;

  .image-preview {
    position: relative;
    display: inline-block;

    .delete-circle {
      position: absolute;
      top: 4px;
      right: 4px;
      width: 16px;
      height: 16px;
      background-color: #ff4d4f;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: white;
      font-size: 12px;

      &:hover {
        background-color: #ff7875;
      }
    }
  }

  .file-preview {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    max-width: 150px;

    .file-name {
      flex: 1;
      word-break: break-all;
      white-space: normal;
      line-height: 1.2;
    }

    .delete-circle {
      width: 16px;
      height: 16px;
      background-color: #ff4d4f;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: white;
      font-size: 12px;
      flex-shrink: 0;
      margin-top: 2px;

      &:hover {
        background-color: #ff7875;
      }
    }
  }
}
</style>
